package com.gjp.etfweb.policys;

import com.gjp.etfweb.bean.FundHistory;
import com.gjp.etfweb.common.Constant;
import com.gjp.etfweb.form.QueryForm;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BoboPolicySalePersent extends BoboPolicy {

    // 卖出份额
    public BigDecimal sale;
    // 止盈点
    public BigDecimal nowStopPoint;

    public BigDecimal saleStep = new BigDecimal(0.2);

    @Override
    public void init(QueryForm queryParam) {
        super.init(queryParam);
        sale = new BigDecimal(0.4);
        nowStopPoint = queryParam.getStopPoint();
    }

    /**
     * 卖出策略
     * 1 年化每到 10% 卖出 20%
     * 2 年化到 15% 卖出 40%
     * 3 年化到 20% 卖出 80%
     * 3 年化到 25% 卖出 100%
     *
     * @param fundHistory
     * @return
     */
    @Override
    public boolean sellPoint(FundHistory fundHistory) {
        // 判断是否达到止盈点，如果达到止盈点，则停止买入，开始止盈
        if (yearEarningsRate.compareTo(nowStopPoint) >= 0) {
            if (totalShare.multiply(averageCost).compareTo(queryParam.getBuyAmount()) <= 0) {

                totalCost = totalCost.add(totalBuyAmount);
                totalProfit = totalProfit.add(totalShare.multiply(fundHistory.getNetWorth()));
                // 清空总份额
                totalShare = BigDecimal.ZERO;
                totalBuyAmount = BigDecimal.ZERO;
                totalDay = BigDecimal.ZERO;
                averageCost = BigDecimal.ZERO;

                stopNum++;
                startTime = null;
                // 全部卖出,还原止盈和卖出份额
                sale = new BigDecimal(0.4);
                nowStopPoint = queryParam.getStopPoint();
            } else {
                // 1 确定卖出份额
                BigDecimal saleShare = totalShare.multiply(sale).setScale(0, RoundingMode.DOWN);
                totalCost = totalCost.add(totalBuyAmount.multiply(sale));
                totalProfit = totalProfit.add(saleShare.multiply(fundHistory.getNetWorth()));

                totalShare = totalShare.subtract(saleShare);
                totalBuyAmount = totalBuyAmount.subtract(totalCost);
                averageCost = totalBuyAmount.divide(totalShare, Constant.DECIMAL_POINT, BigDecimal.ROUND_HALF_UP);

                sale = sale.add(BigDecimal.valueOf(0.2));
                nowStopPoint = nowStopPoint.add(BigDecimal.valueOf(0.05));

                stopNum++;
                startTime = fundHistory.getDate();
            }
            return true;
        }
//        System.out.println("卖出：");
//        printDetails(getFundDetails(fundHistory));
        return false;
    }

}
